import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { useUserStore } from '@/stores/user'

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.set('Authorization', `Bearer ${userStore.token}`)
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, data, message } = response.data

    // 如果没有code，说明是直接返回的数据
    if (code === undefined) {
      return response.data
    }

    // 根据code处理响应
    switch (code) {
      case 0:
        return data
      case 401:
        // Token过期，需要重新登录
        const userStore = useUserStore()
        userStore.logout()
        window.location.href = '/login'
        return Promise.reject(new Error(message || '未授权，请重新登录'))
      default:
        return Promise.reject(new Error(message || '请求失败'))
    }
  },
  (error) => {
    let message = error.message
    if (error.response?.data?.message) {
      message = error.response.data.message
    }
    // 这里可以集成你的消息提示组件
    console.error(message)
    return Promise.reject(error)
  }
)

// 封装GET请求
export const get = <T>(url: string, params?: any): Promise<T> => {
  return request.get(url, { params })
}

// 封装POST请求
export const post = <T>(url: string, data?: any): Promise<T> => {
  return request.post(url, data)
}

// 封装PUT请求
export const put = <T>(url: string, data?: any): Promise<T> => {
  return request.put(url, data)
}

// 封装DELETE请求
export const del = <T>(url: string): Promise<T> => {
  return request.delete(url)
}

export default request
